package com.imist.nettybasic4.utils;

import com.imist.nettybasic4.attribute.Attributes;
import com.imist.nettybasic4.session.Session;
import io.netty.channel.Channel;
import io.netty.channel.group.ChannelGroup;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class SessionUtils {

    //维护tcp连接和用户会话的Map集合
    private static final Map<String ,Channel> userIdChannelMap = new ConcurrentHashMap<>();
    //存放群和群成员组channel的映射
    private static final Map<String, ChannelGroup> groupIdChannelGroupMap = new ConcurrentHashMap<>();

    public static void bindSession(Session session, Channel channel) {
        //将当前用户和tcp连接进行对应并添加到集合中
        userIdChannelMap.put(session.getUserId(),channel);
        //将当前的session对象添加进channel属性
        channel.attr(Attributes.SESSION).set(session);
    }

    public static void unBindSession(Channel channel){
        if (hasLogin(channel)){
            userIdChannelMap.remove(getSession(channel).getUserId());
            channel.attr(Attributes.SESSION).set(null);
        }
    }

    /**
     * 判断是否登陆成功
     * @param channel
     * @return
     */
    public static boolean hasLogin(Channel channel){
        return channel.hasAttr(Attributes.SESSION);
    }

    //获取当前Channel的Session属性
    public static Session getSession(Channel channel) {
        return channel.attr(Attributes.SESSION).get();
    }

    //获取当前用户的Channel
    public static Channel getChannel (String userId){
        return userIdChannelMap.get(userId);
    }


    public static ChannelGroup getChannelGroup(String groupId) {
        return groupIdChannelGroupMap.get(groupId);
    }

    public static void bindChannelGroup(String groupId, ChannelGroup channels) {
        groupIdChannelGroupMap.put(groupId,channels);
    }
}
